package com.groupseven.happycampus.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.groupseven.happycampus.common.bo.BookBo;
import com.groupseven.happycampus.common.instener.WebBookListener;
import com.groupseven.happycampus.common.pojo.Book;
import com.groupseven.happycampus.common.result.R;
import com.groupseven.happycampus.common.utils.OssUtils;
import com.groupseven.happycampus.common.vo.AuthorBarVo;
import com.groupseven.happycampus.common.vo.BookVo;
import com.groupseven.happycampus.common.vo.LayuiPageVo;
import com.groupseven.happycampus.common.vo.SpeciesPieVo;
import com.groupseven.happycampus.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @CreateTime: 2022-07-27 11:13
 * @author: bestzqw
 * @Description:
 */
@RestController
@RequestMapping("/library/book")
public class BookController {

    @Autowired
    private BookService bookService;

    @Autowired
    private WebBookListener webBookListener;


    @RequestMapping("/list")
    //RequestParam 必须加此 注解 否则无法接受到
    public LayuiPageVo<Book> listSeat(@RequestParam Map<String,String> parms){
        System.out.println(parms);
        return bookService.bookList(parms);
    }

    @RequestMapping("/deleteBooks")
    public R deleteAll(@RequestParam("id") String idstr){

        System.out.println(idstr);
        int length = idstr.split(",").length;

        int count = bookService.deleteAll(idstr);

        if (count == length){
            return R.ok();
        }else {
            return R.error();
        }
    }

    @RequestMapping("/update")
    public R updateStudent (Book book){

        System.out.println(book);

        int i = bookService.updateBook(book);

        if (i > 0){
            return R.ok();
        } else {
            return R.error();
        }
    }

    @RequestMapping("/addBook")
    public R addBook(Book book){

        int i = bookService.addBook(book);

        if (i > 0){
            return R.ok();
        } else {
            return R.error();
        }

    }

    @RequestMapping("/upload")
    public R upload(MultipartFile file){

        if (file != null){  //判断空 处理是为了避免 前端的预检查请求
            try {
                String filename = file.getOriginalFilename();
                InputStream inputStream = file.getInputStream();
                String picture = OssUtils.uploadFile(inputStream, filename);
                // 将生成的图片的oss的url地址发送给前端

                return  R.ok().data("picture",picture);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.error();
    }


    // 读取excel 文件数据 存到数据库中
    @RequestMapping("/import")
    public R importExcel(MultipartFile file) throws IOException {
        // 避免预检请求报错
        if(file!=null){
            /**
             * 参数1  文件流
             * 参数2  读取到的数据封装到哪个数据类型中
             * 参数3  监听器  每读取一行数据 就会调用监听器中的 invoke  方法
             * */
            ExcelReaderBuilder read = EasyExcel.read(file.getInputStream(), BookBo.class, webBookListener);
            // 得到 sheet 对象
            ExcelReaderSheetBuilder sheet = read.sheet();
            // 读取sheet
            sheet.doRead();

        }
        return R.ok();
    }

    //导出列表数据   把满足条件的数据 查询出来  写到excel 中  把excel 写到浏览器
    @RequestMapping("/export")
    public void export(Book book,HttpServletResponse response) throws IOException {
        //下载excel 的 响应数据格式
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 下载的文件名 是中文  要进行转码  要不然会出现乱码
        String filename = URLEncoder.encode("图书信息导出", "utf-8");

        // 告诉浏览器  需要下载文件
        response.setHeader("Content-Disposition","attachment;filename="+filename+".xlsx");

        //得到指向浏览器的输出流  向浏览器写输出
        ServletOutputStream outputStream = response.getOutputStream();

        ExcelWriterBuilder write = EasyExcel.write(outputStream, BookBo.class);

        ExcelWriterSheetBuilder sheet = write.sheet();
        //准备满足条件的集合数据
        List<BookBo> bookBos = bookService.bookExcelData(book);
        // 把这个集合数据 写到 输出流
        sheet.doWrite(bookBos);
    }

    // 根据地址分组查询，并将结果封装到 AddressBar 这个类中
    @RequestMapping("/bookBar")
    public R echartBar()  {
        List<AuthorBarVo> list   = bookService.selectByAuthorBar();
        return R.ok().data("list",list);
    }

    // 根据地址分组查询，并将结果封装到 AddressBar 这个类中
    @RequestMapping("/bookPie")
    public R echartsPie()  {
        List<SpeciesPieVo> list   = bookService.selectBySpeciesPie();
        return R.ok().data("list",list);
    }

    //根据地址分组查询，并将结果封装到 AddressBar 这个类中
    @RequestMapping("/group")
    public R bookGroup()  {
        List<BookVo> list   = bookService.bookGroup();
        return R.ok().data("list",list);
    }


    //根据地址分组查询，并将结果封装到 AddressBar 这个类中
    @RequestMapping("/borrow")
    public R borrowBook(@RequestParam("id") Integer id)  {

         int i  = bookService.borrowBook(id);

         if (i>0){
             return R.ok();
         }else {
             return R.error();
         }

    }

    //根据地址分组查询，并将结果封装到 AddressBar 这个类中
    @RequestMapping("/restore")
    public R restoreBook(@RequestParam("id") Integer id)  {
        int i  = bookService.restoreBook(id);
        if (i>0){
            return R.ok();
        }else {
            return R.error();
        }
    }


}
